package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a07_组合总和复习0
 * </p>
 *
 * @author flyduck
 * @since 2025/1/14
 */
public class a07_组合总和复习0 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        traversal(result, path, candidates, target, 0,0);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] nums,
                           int targetSum,
                           int sum,
                           int startIdx){
        if(sum > targetSum){
            return;
        }else if(sum == targetSum) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIdx; i < nums.length; i++) {
            sum = sum + nums[i];
            path.add(nums[i]);
            traversal(result, path, nums, targetSum, sum, i);
            sum = sum - nums[i];
            path.removeLast();
        }
    }
}
